<template>
  <div class="roles-container">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ name: 'welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表--S -->
      <el-table :data="rolesList" stripe style="width: 100%" border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bottom-line', index1 === 0 ? 'top-line' : '']"
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
              class="vcenter"
            >
              <!-- 一级渲染权限 -->
              <el-col :span="5">
                <el-tag>{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级渲染权限 -->
              <el-col :span="19">
                <el-row
                  :class="{ 'top-line': index2 !== 0 }"
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                  class="vcenter"
                >
                  <el-col :span="6">
                    <el-tag type="success">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级权限渲染 -->
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

            <!-- <pre>{{ scope.row }}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRole(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRoleById(scope.row)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="setRights(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 角色列表--E -->
    </el-card>
    <!-- 分配权限对话框--S -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsdialogVisible"
      width="50%"
      @close="rightsArr = []"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsTreeList"
        :props="rightProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="rightsArr"
        ref="rightsRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRightsOnConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框--S -->
    <!-- 添加角色对话框--S -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="50%"
      @close="resetAddRoleForm"
    >
      <el-form
        :model="addRoleRuleForm"
        :rules="addRoleRule"
        ref="addRoleRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleRuleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRoleRuleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框--E -->
    <!-- 编辑角色对话框--S -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoleDialogVisible"
      width="50%"
    >
      <el-form
        :model="editRoleRuleForm"
        :rules="editRoleRule"
        ref="editRoleRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleRuleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleRuleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleOnConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框--E -->
    <!-- 删除角色对话框--S -->
    <!-- 删除角色对话框--E -->
  </div>
</template>

<script>
import {
  getRolesListAPI,
  removeRolesRightsByIdAPI,
  getRightsListAPI,
  resetRolesRightAPI,
  addRoleAPI,
  editRoleAPI,
  deleteRoleAPI
} from '@/api'
export default {
  name: 'RolesIndex',
  data() {
    return {
      rolesList: [],
      rightsTreeList: [],
      rightProps: {
        children: 'children',
        label: 'authName'
      },
      rightsArr: [],
      setRightsdialogVisible: false,
      addRoleDialogVisible: false,
      editRoleDialogVisible: false,
      roleId: '',
      addRoleRuleForm: {
        roleName: '',
        roleDesc: ''
      },
      addRoleRule: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      editRoleRuleForm: {
        roleName: '',
        roleDesc: ''
      },
      editRoleRule: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadingRolesList()
  },
  methods: {
    // 加载角色列表
    async loadingRolesList() {
      try {
        const { data } = await getRolesListAPI()
        if (data.meta.status !== 200) {
          return this.$message.error('获取角色列表失败')
        }
        this.rolesList = data.data
        // console.log(data)
      } catch (err) {
        this.$message.error('获取角色列表失败')
      }
    },
    // 用过 ID 移除权限
    async removeRightById(role, rightId) {
      const res = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(res)
      if (res !== 'confirm') {
        return this.$message.info('已取消删除权限操作')
      }
      // 继续删除操作
      try {
        const { data } = await removeRolesRightsByIdAPI(role.id, rightId)
        console.log(data)
        if (data.meta.status !== 200) {
          return this.$message.error('删除权限失败')
        }
        this.$message.success('删除权限成功')
        this.loadingRolesList()
        // role.children = data.data
      } catch (err) {
        this.$message.error('删除权限失败')
      }
    },
    // 分配权限
    async setRights(role) {
      this.roleId = role.id
      // console.log(role)
      try {
        const { data } = await getRightsListAPI('tree')
        // console.log(data)
        if (data.meta.status !== 200) {
          return this.$message.error('获取权限列表失败')
        }
        this.rightsTreeList = data.data
        this.$message.success('获取权限列表成功')
        this.getThreeRightsId(role, this.rightsArr)
      } catch (err) {
        this.$message.error('获取权限列表失败')
      }
      this.setRightsdialogVisible = true
    },
    // 递归获取所有三级权限 ID
    getThreeRightsId(rights, arr) {
      if (!rights.children) {
        return arr.push(rights.id)
      }
      rights.children.forEach(item => this.getThreeRightsId(item, arr))
    },
    // 确定添加权限处理函数
    async setRightsOnConfirm() {
      const arr = [
        ...this.$refs.rightsRef.getHalfCheckedKeys(),
        ...this.$refs.rightsRef.getCheckedKeys()
      ]
      const newStr = arr.join(',')
      // console.log(newStr)
      try {
        const { data } = await resetRolesRightAPI(this.roleId, newStr)
        // console.log(data)
        if (data.meta.status !== 200) {
          return this.$message.error('添加权限失败')
        }
        this.$message.success('添加权限成功')
        this.loadingRolesList()
        this.setRightsdialogVisible = false
      } catch (err) {
        this.$message.error('添加权限失败')
      }
    },
    // 添加角色
    addRole() {
      // 首先预校验
      this.$refs.addRoleRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        // 校验通过，发请求，渲染数据，关闭弹框
        try {
          const { data } = await addRoleAPI(this.addRoleRuleForm)
          if (data.meta.status !== 201) {
            return this.$message.error('添加角色失败')
          }
          this.loadingRolesList()
          this.addRoleDialogVisible = false
          this.$message.success('添加角色成功')
        } catch (err) {
          this.$message.error('添加角色失败')
        }
      })
    },
    // 重置增加角色表单
    resetAddRoleForm() {
      this.addRoleRuleForm = {
        roleName: '',
        roleDesc: ''
      }
    },
    // 编辑角色
    editRole(role) {
      // console.log(role)
      this.roleId = role.id
      this.editRoleRuleForm.roleName = role.roleName
      this.editRoleRuleForm.roleDesc = role.roleDesc
      this.editRoleDialogVisible = true
    },
    // 编辑角色确认操作
    editRoleOnConfirm() {
      this.$refs.editRoleRef.validate(async valid => {
        if (!valid) return
        try {
          const { data } = await editRoleAPI(this.roleId, this.editRoleRuleForm)
          if (data.meta.status !== 200) {
            return this.$message.error('编辑提交角色失败')
          }
          this.$message.success('编辑角色成功')
          this.loadingRolesList()
          this.editRoleDialogVisible = false
          // console.log(data)
        } catch (err) {
          this.$message.error('编辑提交角色失败')
        }
      })
    },
    // 删除角色
    async deleteRoleById(role) {
      this.roleId = role.id
      const res = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(res)
      if (res !== 'confirm') {
        return this.$message.info('已取消删除角色')
      }
      // 调接口，删除，渲染页面
      try {
        const { data } = await deleteRoleAPI(this.roleId)
        if (data.meta.status !== 200) {
          return this.$message.error('删除角色失败')
        }
        this.$message.success('删除角色成功')
        this.loadingRolesList()
      } catch (err) {
        this.$message.error('删除角色失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
.roles-container {
  .el-tag {
    margin: 8px;
  }
  .top-line {
    border-top: 1px solid #ccc;
  }
  .bottom-line {
    border-bottom: 1px solid #ccc;
  }
  .vcenter {
    display: flex;
    align-items: center;
  }
}
</style>
